package com.gitee.zycra.union.api.common.aspect;

import com.gitee.zycra.union.api.common.util.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zycra
 */
@Slf4j
@Aspect
@Component
public class RequestLogAspect {
    @Pointcut("@within(org.springframework.stereotype.Controller) || @within(org.springframework.web.bind.annotation.RestController)")
    public void pointcut() {
        // 定义切点
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return joinPoint.proceed();
        }
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        String uri = request.getRequestURI();
        Object[] args = joinPoint.getArgs();
        int argLength = args.length;
        String[] jsonArgs = new String[argLength];
        for (int i = 0; i < argLength; i++) {
            jsonArgs[i] = JSONUtil.toJSONString(args[i]);
        }
        long start = System.currentTimeMillis();
        Object result = null;
        try {
            result = joinPoint.proceed();
        } finally {
            log.info("logAspect cost={}, uri={}, args={}, result={}",
                    System.currentTimeMillis() - start, uri, jsonArgs, JSONUtil.toJSONString(result));
        }
        return result;
    }
}
